package org.fioma.tree;

public abstract class SimpleNode<L> implements Node<L> {

	InternalNode<?> parent;
	L label;

	@Override
	public InternalNode<?> getParent() {
		return parent;
	}

	@Override
	public void setParent(InternalNode<?> parent) {
		this.parent = parent;
	}

	@Override
	public L getLabel() {
		return label;
	}

	@Override
	public void setLabel(L label) {
		this.label = label;
	}

	@Override
	public Leaf<?> addNode(int pos, L w) {
		LeafBytes leaf = null;
		if (w.length > 1 && w[0] > 0 && pos >= 0 && pos < getLengthLabel()) {
			if (pos == 0) {
				// create a new child in the parent
				byte bThis = (byte) (getLabel()[1] & 0x03);
				byte bLeaf = (byte) (w[1] & 0x03);
				if (((bThis) ^ (bLeaf)) == 0) {
					System.out.println("2 children start with the same label.");
				}

				leaf = new LeafBytes(getParent(), w);
				leaf.getParent().setChild(leaf, bLeaf);
			} else {
				byte[][] splittedLabels = Tools.splitWord(nodeThis.getLabel(), pos);

				InternalNodeBytes newNode = new InternalNodeBytes(getParent(), splittedLabels[0]);
				leaf = new LeafBytes(newNode, w);

				setLabel(splittedLabels[1]);
				setParent(newNode);

				byte bThis = (byte) (splittedLabels[1][1] & 0x03);
				byte bLeaf = (byte) (w[1] & 0x03);
				byte bNewNode = (byte) (splittedLabels[0][1] & 0x03);

				if (((bThis) ^ (bLeaf)) == 0) {
					System.out.println("2 children start with the same label.");
				}

				newNode.setChild(this, bThis);
				newNode.setChild(leaf, bLeaf);
				newNode.getParent().setChild(newNode, bNewNode);
			}
		} else {
			System.out.println("Position " + pos + " greater or equal than label length " + nodeThis.getLengthLabel());
		}
		return leaf;
	}

}
